package com.goodlearning.gloriamobile.activity;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.codec.binary.Base64;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.TextView;

import com.goodlearning.gloriamobile.R;
import com.goodlearning.gloriamobile.adapter.CustomAdapter;
import com.goodlearning.gloriamobile.adapter.CustomAdapter.IListItemController;
import com.goodlearning.gloriamobile.commons.Utils;
import com.goodlearning.gloriamobile.dto.GetPlanTimeDto;
import com.goodlearning.gloriamobile.net.JsonRequestThread.INetSuccessCallback;
import com.goodlearning.gloriamobile.net.JsonServiceRequester;
import com.goodlearning.gloriamobile.net.JsonWrapper;
/**
 * 
 * 시간표  Activity
 * @author rapty54
 *
 */
public class Plan extends BaseActivity {
	
	ArrayList<GetPlanTimeDto> getPlanTimeDtos;
	
	private JSONArray jsonArray;
	
	private CustomAdapter<GetPlanTimeDto> verticalCustomAdapter;
	
	ListView verticalListView;
	
	int requestCount,dateInit=0;
	
	TextView plan_show_date_TextView,plan_day_of_week,prev_bt,plan_next_Button;

	String week,day,month,year;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.plan_body_layout);
		init();
	}
	/**
	 * 초기 UI 에 Setting 할 View 들을 배치
	 * 요청을 하는 부분은 따로 분리 했다. 초기에 한번만 요청
	 * 1. 초기에 한번만 Json 요청한다.
	 * 2. 단 상단에 Horizontal ListView 클릭시에는 작동 각 날짜에 내용들 
	 *  (토요일/일요일) 건너뛰고 진행한다. 
	 */
	public void init(){
		baseTitleLeftBtn.setVisibility(View.INVISIBLE);
		baseTitleRightBtn.setVisibility(View.INVISIBLE);
		baseTitleTv.setText("내 시간표");
		
		plan_show_date_TextView=(TextView)findViewById(R.id.plan_show_date_TextView);
		plan_day_of_week=(TextView)findViewById(R.id.plan_show_day_of_week);
		
		plan_show_date_TextView.setText
		(Utils.getCurrentDayAdd(dateInit, 0)+"년"
		+Utils.getCurrentDayAdd(dateInit, 1)
		+"월"+Utils.getCurrentDayAdd(dateInit, 2)+"일");
		
		plan_day_of_week.setText(Utils.getCurrentDayAdd(dateInit, 3)+"요일");
		
		prev_bt=(TextView)findViewById(R.id.plan_prev_Button);
		prev_bt.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Utils.log("=====Preview_button=====");

					dateInit--;
					
//					Utils.log("Button_Date_Var:"+"["+dateInit+"]");
					
					year = Utils.getCurrentDayAdd(dateInit, 0);
					month = Utils.getCurrentDayAdd(dateInit, 1);
					day =  Utils.getCurrentDayAdd(dateInit, 2);
					week = Utils.getCurrentDayAdd(dateInit, 3);
					
					Utils.log("======================Date_Info:"+"["+year+"]"+"["+month+"]"+"["+day+"]"+"["+week+"]");
					
				if(!week.equals("토") && !week.equals("일")){
					plan_show_date_TextView.setText(year+"년"+month+"월"+day+"일");
					plan_day_of_week.setText(Utils.getCurrentDayAdd(dateInit, 3)+"요일");
					
					requestJsonGetTimeList(Utils.getCurrentDayAdd(dateInit, 0)+"-"+Utils.getCurrentDayAdd(dateInit, 1)+"-"+Utils.getCurrentDayAdd(dateInit, 2));
					
//					Utils.log("Date_Var:"+"["+dateInit+"]");
				}else{
					dateInit=dateInit-=2;
					
					year = Utils.getCurrentDayAdd(dateInit, 0);
					month = Utils.getCurrentDayAdd(dateInit, 1);
					day =  Utils.getCurrentDayAdd(dateInit, 2);
					week = Utils.getCurrentDayAdd(dateInit, 3);
					
//					Utils.log("Skip_Date_Var:"+"["+dateInit+"]");
					plan_show_date_TextView.setText(year+"년"+month+"월"+day+"일");
					plan_day_of_week.setText(Utils.getCurrentDayAdd(dateInit, 3)+"요일");
					
					requestJsonGetTimeList(Utils.getCurrentDayAdd(dateInit, 0)+
							"-"+Utils.getCurrentDayAdd(dateInit, 1)+
							"-"+Utils.getCurrentDayAdd(dateInit, 2));
				}
			}
		});
		
		plan_next_Button=(TextView)findViewById(R.id.plan_next_Button);
		plan_next_Button.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				
				Utils.log("=====next_button=====");
				
				dateInit++;
				
				year = Utils.getCurrentDayAdd(dateInit, 0);
				month = Utils.getCurrentDayAdd(dateInit, 1);
				day=   Utils.getCurrentDayAdd(dateInit, 2);
				week = Utils.getCurrentDayAdd(dateInit, 3);
				
				Utils.log("======================Date_Info:"+"["+year+"]"+"["+month+"]"+"["+day+"]");
				
				if(!week.equals("토") && !week.equals("일")){
					plan_show_date_TextView.setText(year+"년"+month+"월"+day+"일");
					plan_day_of_week.setText(Utils.getCurrentDayAdd(dateInit, 3)+"요일");
					
					requestJsonGetTimeList(Utils.getCurrentDayAdd(dateInit, 0)+
							"-"+Utils.getCurrentDayAdd(dateInit, 1)+
							"-"+Utils.getCurrentDayAdd(dateInit, 2));
				}else{
					dateInit=dateInit+=2;
					
					year = Utils.getCurrentDayAdd(dateInit, 0);
					month = Utils.getCurrentDayAdd(dateInit, 1);
					day =  Utils.getCurrentDayAdd(dateInit, 2);
					week = Utils.getCurrentDayAdd(dateInit, 3);
					
//					Utils.log("Skip_Date_Var:"+"["+dateInit+"]");
					
					plan_show_date_TextView.setText(year+"년"+month+"월"+day+"일");
					plan_day_of_week.setText(Utils.getCurrentDayAdd(dateInit, 3)+"요일");
					
					requestJsonGetTimeList(Utils.getCurrentDayAdd(dateInit, 0)+
							"-"+Utils.getCurrentDayAdd(dateInit, 1)+
							"-"+Utils.getCurrentDayAdd(dateInit, 2));
				}
			}
		});
		
		verticalListView=(ListView)findViewById(R.id.plan_time_list);
	}
	
	/**
	 * 요청하고자 하는 해당 날짜의 요일을 인수로 전달받아 요청한다.
	 * @param requestCurrentday
	 */
	public void requestJsonGetTimeList(String requestCurrentday){
			JsonServiceRequester.requestGetTimeList(Plan.this,new String(Base64.encodeBase64(getUserId().getBytes())), requestCurrentday, new INetSuccessCallback() {
			
			@Override
			public void sendCallback(JsonWrapper jsonWrapper) {
				
				jsonArray=jsonWrapper.getRootArray();
				
				Utils.log("jsonresultSize:"+"["+jsonArray.size()+"]");
				getPlanTimeDtos=new ArrayList<GetPlanTimeDto>();
				
				for(int i=0;i<jsonArray.size();i++){
					
					JSONObject jsonObject=(JSONObject)jsonArray.get(i);
					
					GetPlanTimeDto getPlanTimeDto=new GetPlanTimeDto();
					
					getPlanTimeDto.setLecInfo(Utils.convertObjToString(jsonObject.get("LecInfo")));
					getPlanTimeDto.setLrcd(Utils.convertObjToString(jsonObject.get("Lrcd")));
					getPlanTimeDto.setGyosi(Utils.convertObjToString(jsonObject.get("gyosi")));
					getPlanTimeDto.setLrNm(Utils.convertObjToString(jsonObject.get("LrNm")));
					
					getPlanTimeDtos.add(getPlanTimeDto);
				}
					setVisibleEmptyAreaOtherType(getPlanTimeDtos.size()<=0);
					
				verticalCustomAdapter=new CustomAdapter<GetPlanTimeDto>(Plan.this, R.layout.plan_vertical_sch_time_row, getPlanTimeDtos, verticallistItemController);
				verticalListView.setAdapter(verticalCustomAdapter);
			}});
	}
	
	/**
	 *  부가적으로 연속적 호출이 남발되는 현상을 제어한다.
	 *  최초 실행시에는 현재 날짜를 반드시 가져오므로 현재 날짜의 서비스 요청 결과 초기화
	 *  나머지 실행 부분은 Horizontal ListView 에서 클릭시 각자의 일자 서비스 결과를 가져온다.
	 *  추가적인 요청 방지 및  System call memory Lick 방지
	 */
	protected void onResume() {
		super.onResume();
		
		Utils.log("===========onResume========");
		
		requestCount++;
		
		if(requestCount==1){
			Utils.log("GetCurrentToday:"+"["+Utils.getCurrentToday(dateInit)+"]");
			requestJsonGetTimeList(Utils.getCurrentToday(dateInit));
		}
	};
	
	/**
	 * 
	 * vertical Controller Custom 정의 다음으로 넘길 객체에 대한 정의도 포함한다.
	 * 내용물 출력 
	 */
	IListItemController<GetPlanTimeDto> verticallistItemController=new IListItemController<GetPlanTimeDto>() {

		@Override
		public View controlView(List<GetPlanTimeDto> items, int position, View convertView,ViewGroup parent) {
			
			GetPlanTimeDto showResult=(GetPlanTimeDto)items.get(position);
			
			String LecInfo=showResult.getLecInfo();
			String Gyosi=showResult.getGyosi();
			String LrNm=showResult.getLrNm();
			
			((TextView)convertView.findViewById(R.id.plan_sch_class_time)).setText(Gyosi+"교시");
			((TextView)convertView.findViewById(R.id.plan_sch_class_subject_n_name)).setText(LecInfo);
			((TextView)convertView.findViewById(R.id.plan_sch_class_building_name)).setText(LrNm);
			
			Utils.log("Class_Time:"+Gyosi+"LecInfo:"+LecInfo+"LrNm:"+LrNm);
			return convertView;
		}
	};
	/**
	 * 종료와 동시에 logout 도 모두 한다.
	 */
	@Override
	public void onBackPressed() {
		Utils.showConfirmDialog(Plan.this, "종료", "글로리아 모바일을 종료 하시겠습니까?", new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				
				allClearActivity();
				
			}
		}, null);
	}
}
